using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using WorldEditSupport;
using TextSupport;

namespace WorldEdit
{
	public partial class EditContainer : UserControl, IEditSurface
	{
		WorldDoc _doc = new WorldDoc();
		Outline _outline;
		OutlineController _outlineController;
		OutlineView _outlineView;

		Font _defaultFont;

		[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public WorldDoc Document
		{
			set 
			{ 
				_doc = value;

				_outline = new Outline(_doc.OutlineBody);
				_outlineView = new OutlineView(_outline, this);
				_outlineController = new OutlineController(_outline, _outlineView);

				// Initial layout
				if (Width != 0)
				{
					_outlineController.Layout();
					Invalidate();
					UpdateScrollBars();
				}
			}

			get { return _doc; }
		}

		public EditContainer()
		{
			InitializeComponent();

			VerticalScroll.Visible = true;

			SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserMouse | ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint, true);

			_defaultFont = new Font("Tahoma", 10);

			// Something to hold onto while we initialize
			WorldDoc emptyDoc = new WorldDoc();
			Document = emptyDoc;
		}

		private void EditContainer_SizeChanged(object sender, EventArgs e)
		{
			if (Width > 0)
			{
				_outlineController.Layout();

				UpdateScrollBars();
			}
		}

		private void UpdateScrollBars()
		{
			if (_outlineView.Height > Height)
			{
				VerticalScroll.Enabled = true;
				VerticalScroll.Minimum = 0;
				VerticalScroll.Maximum = (int)_outlineView.Height - Height;
				VerticalScroll.LargeChange = Height;
				VerticalScroll.Value = 0;
			}
			else
			{
				VerticalScroll.Enabled = false;
			}
		}

		#region IEditSurface Members

		public RectangleF GetExtent()
		{
			return ClientRectangle;
		}

		Graphics TextSupport.IEditSurface.GetGraphics()
		{
			return Graphics.FromHwnd(Handle);
		}

		public Font GetDefaultFont()
		{
			return _defaultFont;
		}

		void TextSupport.IEditSurface.Invalidate(RectangleF rect)
		{
			base.Invalidate(new Rectangle((int)rect.Left, (int)rect.Top, (int)rect.Right, (int)rect.Bottom));
		}

		public Graphics GetGraphics()
		{
			throw new Exception("The method or operation is not implemented.");
		}

		public void Invalidate(RectangleF rect)
		{
			throw new Exception("The method or operation is not implemented.");
		}

		public void RestartCaretTimer()
		{
			throw new Exception("The method or operation is not implemented.");
		}

		#endregion

		protected override void OnPaint(PaintEventArgs e)
		{
			base.OnPaint(e);
			_outlineView.Paint(e);
		}
	}
}
